<template>
  <view class="container">
    <scroll-view scroll-y="true" class="agent_info">
      <view style="padding-bottom: 50rpx">
        <view v-if="aiInfo.createrId == useToken.user.userId">
          <view class="user-info">
            <img :src="aiInfo.avatarUrl" class="user-img" />
            <uni-icons
              class="add-avatar"
              type="plus-filled"
              color="#0092FF"
              size="40"
              @click="chooseFile"
            />
          </view>
          <view class="form-item name">
            <view class="title">名称</view>
            <input
              cursor-spacing="100"
              placeholder="智能体名称"
              v-model="aiInfo.nickname"
            />
          </view>
          <view class="form-item">
            <view class="title">设定描述</view>
            <textarea
              :disable-default-padding="true"
              cursor-spacing="100"
              v-model="aiInfo.agentDescription"
              placeholder="示例：你是一位经验丰富的英语老师，拥有激发学生学习热情的教学方法。你善于运用幽默和实际应用案例，使对话充满趣味。"
            />
          </view>
          <view class="form-item">
            <view class="title">设定开场白</view>
            <textarea
              :disable-default-padding="true"
              cursor-spacing="100"
              v-model="aiInfo.prologue"
              placeholder="将作为开启聊天的第一句话"
            />
          </view>
          <view class="form-card">
            <view class="form-card-item" style="border: 0 none">
              <view class="title">语言</view>
              <view class="text" @tap="showPicker('language')">
                <view>{{ pickerData.languageName || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title">性别</view>
              <view class="text" @tap="showPicker('sex')">
                <view>{{ pickerData.sexName || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title">声音</view>
              <view class="text" @tap="showPicker('voice')">
                <view>{{ aiInfo.voiceName || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title">公开性</view>
              <view class="text" @tap="showPicker('isOpen')">
                <view>{{ pickerData.isOpenName || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title" style="width: 30%">对话风格</view>
              <view class="text">
                <input
                  placeholder="例：甜美风"
                  v-model="aiInfo.languageStype"
                />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title" style="width: 30%">技能</view>
              <view class="text">
                <input placeholder="例：唱歌" v-model="aiInfo.skills" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title" style="width: 30%">口头禅</view>
              <view class="text">
                <input placeholder="例：嗯嗯" v-model="aiInfo.petPhrase" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title">爱好</view>
              <view class="text" @tap="showPickerCustom('hobby')">
                <view>{{ translateText("hobby") || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
            <view class="form-card-item">
              <view class="title">职业</view>
              <view class="text" @tap="showPickerCustom('career')">
                <view>{{ translateText("career") || "请选择" }}</view>
                <uni-icons type="right" size="16" style="margin-left: 20rpx" />
              </view>
            </view>
          </view>
          <view class="form-item clear" @tap="clear">
            <view class="title">清空上下文</view>
          </view>
          <button type="primary" class="save" @tap="saveAI">保存智能体</button>
        </view>
        <view v-else>
          <view class="user-info">
            <img :src="aiInfo.avatarUrl" class="user-img" />
          </view>
          <view class="form-item name">
            <view class="title">智能体名称</view>
            <text class="no-edit-txt">
              {{ aiInfo.nickname }}
            </text>
          </view>
          <view class="form-item name">
            <view class="title">智能体描述</view>
            <text class="no-edit-txt" style="flex: 1">{{
              aiInfo.agentDescription
            }}</text>
          </view>
          <view class="form-item clear" @tap="clear">
            <view class="title">清空上下文</view>
          </view>
        </view>
      </view>
      <u-picker
        v-if="pickerShow"
        :show="pickerShow"
        :columns="columns"
        keyName="showName"
        :defaultIndex="defaultIndex"
        @confirm="pickerConfirm"
        @cancel="pickerShow = false"
      ></u-picker>
    </scroll-view>
    <popupTag @confirmData="getTagsContet" :tasgData="tasgData" />
  </view>
</template>

<script setup>
import {
  editAgent,
  getAgentAttr,
  getVoiceAttr,
  clearAgentContext,
} from "@/global/agentApi";
import popupTag from "./coms/popupTag.vue";
import { setRedis } from "@/global/chatApi";

import useLogin from "@/store/useLogin.js";
import useAgent from "@/store/useAgent.js";
import useChat from "@/store/useChat.js";

const useAgentStore = useAgent();
const useLoginStore = useLogin();
const useChatStore = useChat();
let aiInfo = ref({ ...useAgentStore.agentInfo });
let pickerData = reactive({
  voiceList: [],
  sexList: [],
  languageList: [],
  isOpenList: [],
  hobbyList: [],
  careerList: [],
  languageName: "中文",
  isOpenName: "",
  sexName: "",
  hobbyName: "",
  careerName: "",
});
let columns = ref([]);
let defaultIndex = ref([0]);
let pickerShow = ref(false);
let pickerType = ref("");
//传入到popupTags组件的数据
const tasgData = ref({
  tagsList: [], //tag列表
  tagsFlag: false, //是否展示popup
  tagsContent: "", //输入框
  tagsChecked: [], //默认选中的
});

//自定义的弹框选项（多选tag和输入框） 打开
const showPickerCustom = (type) => {
  pickerType.value = type;
  tasgData.value.tagsList = pickerData[`${type}List`];
  tasgData.value.tagsFlag = true;
  tasgData.value.tagsChecked = aiInfo.value[`${pickerType.value}`] || [];
  tasgData.value.tagsContent = aiInfo.value[`${type}Customize`];
};

//确认事件
const getTagsContet = (data) => {
  tasgData.value.tagsFlag = false;
  aiInfo.value[`${pickerType.value}`] = data.tagsChecked;
  aiInfo.value[`${pickerType.value}Customize`] = data.tagsContent;
};

//弹框tag选中和输入框后转文字展示
const translateText = (key) => {
  let str = "";
  let checkedList = aiInfo.value[`${key}`]; //已选中的tag集合
  if (checkedList) {
    checkedList.map((name, index) => {
      str += name + (index === checkedList.length - 1 ? "" : ",");
    });
    return (
      str +
      (aiInfo.value[`${key}Customize`]
        ? (str ? "," : "") + aiInfo.value[`${key}Customize`]
        : "")
    );
  }
  return "";
};

const clear = () => {
  console.log(useChatStore);
  uni.showModal({
    title: "提示",
    content: "确定要清除此智能体的上下文吗",
    success: function (res) {
      if (res.confirm) {
        clearAgentContext({
          agentId: useAgentStore.agentId,
          userId: useLoginStore.user.userId,
          nickName: useLoginStore.user.nickname,
          groupId: useChatStore.currentSessionId,
        }).then((res) => {
          if (res && res.code == 200) {
            useChatStore.clearMsgAndGroupId(res.data);
            uni.showToast({
              title: "上下文已清空",
              icon: "success",
              duration: 3000,
            });
            uni.navigateBack();
          }
        });
      } else if (res.cancel) {
        console.log("用户取消清除");
      }
    },
  });
};

const showPicker = (type) => {
  pickerType.value = type;
  columns.value = [pickerData[`${type}List`]];
  let key = "";
  switch (type) {
    case "voice":
      key = "voiceId";
      break;
    default:
      key = `${type}Code`;
      break;
  }
  if (aiInfo.value[key]) {
    for (let index in pickerData[`${type}List`]) {
      if (pickerData[`${type}List`][index].dictCode === aiInfo.value[key]) {
        defaultIndex.value = [+index];
        break;
      }
    }
  } else {
    defaultIndex.value = [0];
  }
  pickerShow.value = true;
};

const pickerConfirm = (val) => {
  let key = "";
  switch (pickerType.value) {
    case "voice":
      key = "voiceId";
      break;
    default:
      key = `${pickerType.value}Code`;
      break;
  }
  aiInfo.value[key] = val.value[0].dictCode;
  if (pickerType.value === "voice") {
    aiInfo.value.voiceName = val.value[0].showName;
  } else {
    pickerData[`${pickerType.value}Name`] = val.value[0].showName;
  }
  pickerShow.value = false;
};

const saveAI = () => {
  if (!aiInfo.value.nickname) {
    uni.showToast({
      title: `昵称不能为空,请输入昵称`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  if (!aiInfo.value.agentDescription) {
    uni.showToast({
      title: `描述不能为空,请输入描述`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  let agentId = aiInfo.value.id;
  delete aiInfo.value.id;
  aiInfo.value.userId = uni.getStorageSync("currentUserId");
  editAgent(aiInfo.value).then((res) => {
    if (res.code === 200) {
      setRedis({
        userId: uni.getStorageSync("currentUserId"),
        agentId: agentId,
      });
      aiInfo.value.id = agentId;
      delete aiInfo.value.userId;
      useAgentStore.agentInfo = aiInfo.value;
      uni.showToast({
        title: "保存成功",
        icon: "success",
        duration: 3000,
      });
      uni.navigateBack();
    }
  });
};

const chooseFile = () => {
  uni.chooseImage({
    count: 1,
    mediaType: ["image"],
    sizeType: ["compressed"],
    camera: "back",
    success: (res) => {
      let baseUrl = import.meta.env.VITE_APP_BASE_API_CHAT;
      aiInfo.value.avatarUrl = res.tempFilePaths[0];
      uni.showLoading({
        title: "加载中",
      });
      uni.uploadFile({
        url: baseUrl + "/chatmgt/app/avatar",
        filePath: res.tempFiles[0].path || "",
        name: "avatarFile",
        formData: {},
        headers: { "Content-Type": "multipart/form-data" },
        success: (uploadFileRes) => {
          let res = JSON.parse(uploadFileRes.data);
          if (res.code == 200) {
            let url = res.data;
            aiInfo.value.avatarUrl = url;
            uni.hideLoading();
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "error",
              title: uploadFileRes.errMsg,
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            icon: "error",
            title: JSON.stringify(err),
          });
          console.log("图片上传接口调用失败", err);
        },
      });
    },
  });
};

onShow(() => {
  getAgentAttr().then((res) => {
    pickerData.languageList = res.data.languageList;
    pickerData.sexList = res.data.sexList;
    pickerData.isOpenList = res.data.isOpenList;
    pickerData.hobbyList = res.data.hobbyList;
    pickerData.careerList = res.data.careerList;
    if (aiInfo.value.languageCode) {
      for (let item of pickerData.languageList) {
        if (item.dictCode === aiInfo.value.languageCode) {
          pickerData.languageName = item.showName;
          break;
        }
      }
    }
    if (aiInfo.value.sexCode) {
      for (let item of pickerData.sexList) {
        if (item.dictCode === aiInfo.value.sexCode) {
          pickerData.sexName = item.showName;
          break;
        }
      }
    }
    if (aiInfo.value.isOpenCode) {
      for (let item of pickerData.isOpenList) {
        if (item.dictCode === aiInfo.value.isOpenCode) {
          pickerData.isOpenName = item.showName;
          break;
        }
      }
    }
    if (aiInfo.value.hobbyCode) {
      for (let item of pickerData.hobbyList) {
        if (item.dictCode === aiInfo.value.hobbyCode) {
          pickerData.hobbyName = item.showName;
          break;
        }
      }
    }
    if (aiInfo.value.careerCode) {
      for (let item of pickerData.careerList) {
        if (item.dictCode === aiInfo.value.careerCode) {
          pickerData.careerName = item.showName;
          break;
        }
      }
    }
  });
  getVoiceAttr().then((res) => {
    pickerData.voiceList = res.rows.map((item) => {
      item.showName = item.voiceName;
      item.dictCode = item.voiceId + "";
      return item;
    });
  });
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}
.no-edit-txt {
  font-size: 32rpx;
}
</style>
